package com.jx.lcs.employee.web;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jx.lcs.employee.entity.Employee;
import com.jx.lcs.employee.service.EmployeeService;
import com.jx.lcs.user.entity.UserInfo;
import com.jx.lcs.user.service.UserInfoService;
import com.jx.lcs.util.common.IdCardUtil;
import com.tianyu.jty.common.persistence.Page;
import com.tianyu.jty.common.persistence.PropertyFilter;
import com.tianyu.jty.common.utils.DateUtils;
import com.tianyu.jty.common.web.BaseController;

/** 
 * 理财师controller
 * @author JiaYY 
 * @date 2015年7月2日
 */
@Controller
@RequestMapping("employee")
public class EmployeeController extends BaseController {
	
	private static final Logger logger = LoggerFactory.getLogger(EmployeeController.class);

	@Autowired
	private EmployeeService employeeService;
	
	@Autowired
	private UserInfoService userInfoService;
	
	/**
	 * 默认页面
	 */
	@RequestMapping(method = RequestMethod.GET)
	public String list() {
		return "employee/employeeList";
	}
	
	/**
	 * 获取理财师列表json
	 */
	@RequestMapping(value="json",method = RequestMethod.GET)
	@ResponseBody
	public Map<String, Object> employeeList(HttpServletRequest request) {
		try{
			Page<Employee> page = getPage(request);
			List<PropertyFilter> filters = PropertyFilter.buildFromHttpRequest(request);
			page = employeeService.search(page, filters);
			Map<String, Object> result = getEasyUIData(page);
			List<Employee> list = (List<Employee>) result.get("rows");
			if(list != null && list.size() > 0) {
				for(Employee employee : list) {
					employee.setCardNo(IdCardUtil.getIdCardEcp(employee.getCardNo()));
				}
			}
			return result;
		}catch(Exception e){
			logger.error("--获取理财师列表出现异常！", e);
			return null;
		}
	}
	
	/**
	 * 添加理财师跳转
	 * 
	 * @param model
	 */
	@RequestMapping(value = "create", method = RequestMethod.GET)
	public String createForm(Model model) {
		model.addAttribute("employee", new Employee());
		model.addAttribute("action", "create");
		return "employee/employeeForm";
	}

	/**
	 * 添加理财师
	 * 
	 * @param employee
	 * @param model
	 */
	@RequestMapping(value = "create", method = RequestMethod.POST)
	@ResponseBody
	public String create(@Valid Employee employee, Model model) {
		try{
			String telephone = employee.getTelephone();
			String userCode = employee.getUserCode();
			String jxId = employee.getJxId();
			
			telephone = telephone.trim();
			if(userCode != null) {
				userCode = userCode.trim();
			} else {
				userCode = "";
			}
			
			if("".equals(userCode)) {
				return "员工号不能为空！";
			}
			
			if(jxId != null) {
				jxId = jxId.trim();
			} else {
				jxId = "";
			}
			
			
			if("".equals(telephone)) {
				return "请输入手机号！";
			} else {
				Employee epy = employeeService.findByTelephone(telephone);
				if(epy != null) {
					return "该手机号已存在！";
				}
				if("".equals(userCode)) {
					boolean flag = false;
					Employee emp = null;
					while(!flag) {
						int code = (int)((Math.random() * 9 + 1) * 1000000);
						userCode = "8" + code;
						
						emp = employeeService.findByUserCode(userCode);
						if(emp == null) flag = true;
					}
					
					employee.setUserCode(userCode);
				} else {
					epy = employeeService.findByUserCode(userCode);
					if(epy != null) {
						return "该员工号已存在！";
					}
					
					if(!"".equals(jxId)) {
						epy = employeeService.findByJxId(jxId);
						if(epy != null) {
							return "该邀请码已存在！";
						}
					}
				}
				
				if ("".equals(employee.getId()))
					employee.setId(null);
				employee.setCreateTime(DateUtils.getSysDate());
				
				employeeService.save(employee);
			}
			return "success";
		}catch(Exception e){
			logger.error("--添加理财师出现异常！！", e);
			
			return "添加理财师失败";
		}
	}
	
	/**
	 * 修改理财师信息跳转
	 * 
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "update/{id}", method = RequestMethod.GET)
	public String updateForm(@PathVariable("id") String id, Model model) {
		model.addAttribute("employee", employeeService.get(id));
		model.addAttribute("action", "update");
		return "employee/employeeForm";
	}

	/**
	 * 修改理财师信息
	 * 
	 * @param employee
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "update", method = RequestMethod.POST)
	@ResponseBody
	public String update(@Valid @ModelAttribute @RequestBody Employee employee, Model model) {
		try{
			Employee employeeInfo = employeeService.get(employee.getId());
			if(employeeInfo != null) {
				String jxId = employee.getJxId().trim();
				String city = employee.getCity().trim();
				String userDept = employee.getUserDept().trim();
				String userPost = employee.getPost().trim();
				
				employeeInfo.setJxId(jxId);
				employeeInfo.setCity(city);
				employeeInfo.setUserDept(userDept);
				employeeInfo.setPost(userPost);
				
				UserInfo userInfo = null;
				if(!StringUtils.isBlank(employeeInfo.getUserCode())) {
					userInfo = userInfoService.getEntityDao().findUniqueBy("uid", employeeInfo.getUserCode());
				}
				
				if(userInfo != null) {
					userInfo.setJxId(jxId);
					userInfo.setCity(city);
					userInfo.setUserDept(userDept);
					userInfo.setPostLevel(userPost);
				}
				
				employeeService.updateEmployee(employeeInfo, userInfo);
			}
			
			return "success";
		}catch(Exception e){
			logger.error("--修改理财师信息出现异常！！", e);
			
			return "修改理财师信息失败";
		}
	}
	
}
